require("./index.scss");
var Pagination = require("COMMON/modules/pagination-x/v1.0");
var Select = require("COMMON/modules/select");
var Tpl = require("./tpl/index.xtpl");
var Ly = require("./tpl/ly.xtpl");
var OptModal = require("./tpl/operatemodal.xtpl");
var Company = require("./tpl/company.xtpl")
var Address = require("./tpl/address.xtpl");
var LyName = require("./tpl/getlyname.xtpl");
var cData = require("COMMON/js/config.province.city.data");
var ProvCitySelector = require("COMMON/Components/ProvCitySelect/v1.0/");
var ImgUploador = require("../mem");
var ParseTemplate = ZFT.Util.ParseTemplate;
var Template = {
    option: ParseTemplate(require("./tpl/select.xtpl")),
    lymodal: ParseTemplate(require("./tpl/lymodal.xtpl")),
    fymodal: ParseTemplate(require("./tpl/fymodal.xtpl")),
    addlyimg: ParseTemplate(require("./tpl/addlyimgdiv.xtpl")),
    addfyimg: ParseTemplate(require("./tpl/addfyimgdiv.xtpl")),
    editlymodal: ParseTemplate(require("./tpl/editlymodal.xtpl")),
    editfymodal: ParseTemplate(require("./tpl/editfymodal.xtpl")),
    ratebox: ParseTemplate(require("./tpl/fyrate.xtpl")),
    lycntbox: ParseTemplate(require("./tpl/cntbox.xtpl"))
};
var Building = ZFT.Util.Class({
    container: $("body"),
    init: function () {
        var that = this;
        var schBtn = $("#schFy"); //搜索房源
        var schLyBtn = $("#schLyBtn");//搜索楼宇
        var headTab = $("#headTab");//tab页
        var word = decodeURI(window.parent.location.search.substr(6, window.parent.location.search.length));//获取关键字;
        var paginationLy, pagination;
        var pers = that.pers = ZFT.Util.getPermission(),
            addLyBtn = '<button id="addLy" class="m-btn m-btn_ol_default  newBtn">新增楼宇</button>',
            addFyBtn = '<button id="addFy" class="m-btn m-btn_ol_default  newBtn">新增房源</button>';
        $("#addFyDiv").html(($.inArray("31", pers) !== -1) && addFyBtn);
        //切换tab页
        headTab.on("click", ".m-head_tab_title", function (e) {
            var _this = $(e.currentTarget);
            var getLy = $("#switchLy"),
                getFy = $("#switchFy");
            if (_this.hasClass("fy", "noactive")) {
                _this.removeClass("noactive").siblings().addClass("noactive").siblings("#addFyDiv").html(($.inArray("31", pers) !== -1) && addFyBtn);
                getFy.fadeIn(200).show();
                getLy.fadeIn(200).hide();

            } else if (_this.hasClass("ly", "noactive")) {
                _this.removeClass("noactive").siblings().addClass("noactive").siblings("#addFyDiv").html(($.inArray("34", pers) !== -1) && addLyBtn);
                getFy.fadeIn(200).hide();
                getLy.fadeIn(200).show();
            }
        });
        pagination = this.pagination = new Pagination({
            container: $(".paginationWrap"),
            count: 5,
            showTotal: true,
            jump: true,
            filter: true
        });
        pagination.on("page.switch", function (toPage, currentPage, totalPage) {
            pagination.render({ current: currentPage, toPage: toPage }),
                that.getBuildingList(toPage);
        });
        paginationLy = this.paginationLy = new Pagination({
            container: $(".paginationWrapLy"),
            count: 5,
            showTotal: true,
            jump: true,
            filter: true
        });
        paginationLy.on("page.switch", function (toPage, currentPage, totalPage) {
            paginationLy.render({ current: currentPage, toPage: toPage }),
                that.getLyList(toPage);
        });
        that.getBuildingList(1);
        $("#schLyInp").val(word);
        that.getLyList(1);
        schBtn.on("mousedown", function (e) {
            var tarBtn = $(e.currentTarget);
            tarBtn.attr("data-id", "");
        })
        schBtn.on("click", function () {
            that.getBuildingList(1);
        });
        schLyBtn.on("click", function (e) {
            word = "";
            that.getLyList(1);
        });

        that.initLocation('schPro', 'schCity', 'schArea');
        that.initLocation('schProLy', 'schCityLy', 'schAreaLy');
        that.container.on("click", ".close,.cancel", function (e) {
            that.closeModal(e);
        });
    },

    EVENTS: {
        "click #addLy": "addLy",
        "click #addFy": "addFy",
        "click #saveLy": "editOrSaveLy",
        "click #saveFy": "editOrSaveFy",
        "click #saveEdLy": "editOrSaveLy",
        "click #saveEdFy": "editOrSaveFy",
        "change #getLyName": "switchBuildingArea",
        "click .g-table .corp .u-btn_del": "openStatusModal",
        "click .g-table .corp .u-btn_edi": "openEditModal",
        "click .g-table .corp .u-btn_inv": "openStatusModal",
        "click .m-modal_bg .u-modal-btn_conf": "onClickModalConfBtn",
        "click .del-btn": "onClickImgDivDelbtn",
        "click .bname": "onClickAreaTd"
    },
    //切换楼宇管理与房源管理Tab页
    switchTab: function (e) {
        var $this = $(this);
        if ($this.has(".noactive")) {
            $this.removeClass("noactive")
        }
    },
    //初始化区域
    initLocation: function (prov_id, city_id, area_id, pro_val, city_val) {
        var that = this;
        var locationSelect = new ProvCitySelector({
            provId: '#' + prov_id,
            cityId: '#' + city_id,
            onProvChange: function (provId) {
                var areaSelect = $("#" + area_id);
                var option = '<option value="0">请选择</option>';
                areaSelect.show().html(option);                //当省下拉框变化时执行的回调函数，参数为 省下拉框中 所选省份对应的省份代号
            },
            onCityChange: function (cityId) {           //当省下拉框变化时执行的回调函数，参数为 市下拉框中 所选城市对应的城市代号

                that.ajaxRenderDistrict(cityId, area_id);
            },
            afterLoading: function () {
                that.ajaxRenderDistrict($('#' + city_id).val(), area_id);
            }
        });
        if (pro_val && city_val) {
            locationSelect.setVal(pro_val, city_val);
        }
    },
    //初始化出租率
    initRatebox: function (param) {
        ZFT.Util.Ajax("/r/building_getHouseSummary", {
            type: "POST",
            dataType: "json",
            params: param,
            success: function (res) {
                var html = Template.ratebox({ data: res.data });
                $("#rateDiv").html(html);
            }
        })
    },
    //初始化楼宇统计
    loadCntBox: function () {
        ZFT.Util.Ajax("/r/Building_getBuildingStatics", {
            type: "POST",
            dataType: "json",
            success: function (res) {
                var dtype = ZFT.Util.getDtype();
                if (dtype == 0 || dtype == 1 || dtype == 2 || dtype == 5 || dtype == 6) {
                    $("#tabLy,#switchLy").empty();
                    //$("#switchLy").html("");
                }
                if (res.code == 200) {
                    var html = Template.lycntbox({ data: res.data });
                    $("#cntBox").html(html);
                }
            }
        })
    },
    //获取区域地址
    ajaxRenderDistrict: function (cityId, area_id, country_name) {
        var areaSelect = $("#" + area_id);
        if (!cityId) {
            areaSelect.html('<option value="0">请选择</option>');
            return false;
        }
        var _this = this;
        ZFT.Util.Ajax(
            '/index/getCountry.html',
            {
                type: 'POST',
                params: {
                    city_id: cityId
                },
                success: function (res) {
                    var html = '<option value="0">请选择</option>';
                    var list = res.data.list;
                    if (res.code == 200) {
                        if (country_name) list["name"] = country_name;
                        html += Template.option({ data: list });
                        areaSelect.html(html);
                    } else {
                        areaSelect.hide()
                    }
                },
                serverError: function (xhr, txt) {

                }
            }

        )
    },
    //获取省,市,区域具体列表
    initAddress: function (uri, provId) {
        var that = this;
        if ($("#" + provId + " option").size() > 1) return false;
        ZFT.Util.Ajax(
            uri,
            {
                type: "POST",
                dataType: "json",
                success: function (res) {
                    var list = res.data.list;
                    var areaSelect = $("#" + provId);
                    var areaSelectVal = areaSelect.val(); //省,市自身的val值
                    var city_areaId = "";
                    var city_areaVal = "";
                    var dataParam = "";
                    var render = ZFT.Util.ParseTemplate(Address);
                    var option = "<option value='0'>请选择</option>"
                    that.initProvCityArea(provId);
                    switch (res.code) {
                        case 200:
                            var html = render({ provArr: list });
                            areaSelect.html(option + html); //将省,市,区列表添加到select
                            break;
                    }
                }
            });
    },
    //获取城市或者城镇列表
    getCityArea: function (uri, provId, dataParam) {
        ZFT.Util.Ajax(
            uri,
            {
                type: "POST",
                dataType: "json",
                params: dataParam,
                success: function (res) {
                    var list = res.data.list;
                    var areaSelect = $("#" + provId);
                    var render = ZFT.Util.ParseTemplate(Address);
                    var option = "<option value='0'>请选择</option>"
                    switch (res.code) {
                        case 200:
                            var html = render({ provArr: list });
                            areaSelect.html(option + html); //将省,市,区列表添加到select
                            break;
                    }
                }
            });
    },

    //切换时重新初始化三级联动
    initProvCityArea: function (provId) {
        var provSelect = $("#" + provId);
        var cityId = provSelect.siblings(".city").attr("id");
        var areaId = provSelect.siblings(".area").attr("id");
        var option = "<option value='0'>请选择</option>"
        $("#" + cityId + ",#" + areaId).html(option);
    },


    //获取房源列表
    getBuildingList: function (toPage, id) {
        var that = this;
        var tbody = $("#tbody");
        var page = $(".paginationWrap");
        var countrySelected = $("#schArea option:selected");
        var countryVal = $("#schArea").val();
        var country = (countryVal == "0") ? countryVal : $("#schArea option:selected").text();
        var page_size = page.attr("data-size");
        var id = $("#schFy").attr("data-id");
        var param = {
            id: id ? id : "",
            province: $("#schPro").val(),
            city: $("#schCity").val(),
            country: country,
            name: $("#schFyInp").val(),
            status: $("#statusFy").val(),
            is_delete: $("#isdelFy").val(),
            trade_area: $("#tradeAreaFy").val(),
            room: $("#room").val(),
            page: toPage,
            page_size: page_size ? page_size : 10,
        };

        ZFT.Util.Ajax(
            "/r/building_index",
            {
                type: "POST",
                dataType: "json",
                params: param,
                loading: function () {
                    var html = '<tr><td colspan="8">加载中,请稍后...</td></tr>'
                    tbody.html(html);
                    page.hide();
                },
                success: function (res) {
                    var list = res.data.list;
                    var render = ZFT.Util.ParseTemplate(Tpl);
                    var dtype = res.data.dtype;
                    var pers = that.pers;
                    page.hide();
                    if (dtype == 1 || dtype == 3 || dtype == 4) {
                        that.initRatebox(param);
                    }
                    if (res.code == 200) {
                        if (list) {
                            var html;
                            for (var i = 0, len = list.length; i < len; i++) {
                                var item = list[i];
                                var prov = item.province;
                                var city = item.city;
                                var area;
                                if (!prov) continue;
                                area = that.getLocationName(prov, city);
                                item["city_area"] = area;
                            }

                            list["dtype"] = dtype;
                            list["unsetBtn"] = ($.inArray("32", pers) !== -1) ? 1 : 0;
                            list["delBtn"] = ($.inArray("33", pers) !== -1) ? 1 : 0;
                            html = render({ array: list }, that);
                            tbody.html(html);
                            that.pagination.render({ current: toPage, toPage: toPage, total: res.data.total });
                        } else {
                            return tbody.html('<tr><td colspan="8">暂无数据</td></tr>');

                        }
                    } else if (res.code == 102) {
                        var relogin = '<tr><td colspan="8"><a href="index/logOut">未登录,请重新登录</a></td></tr>'
                        tbody.html(relogin);
                    } else {
                        var html = '<tr><td colspan="8">' + res.msg + '</td></tr>'
                        tbody.html(html);
                    }
                }
            })
    },
    //通过区域码获取对应名称
    getLocationName: function (prov, cityId) {
        if (!prov) return false;
        var province = cData[prov];
        var prov_name = province.name;
        var citys = province.city;
        var city_name = "";
        for (var i = 0; i < citys.length; i++) {
            var city = citys[i];
            var city_id = city.id;
            if (city_id == cityId) {
                city_name = city.name;
                break;
            }
        }
        return prov_name + " " + city_name;
    },
    //显示新增楼宇div
    addLy: function () {
        var that = this;
        var lyModal = Template.lymodal();
        var type = "ly";

        $("#modal").html(lyModal)
        that.initLocation('schProFyLy', 'schCityFyLy', 'schAreaFyLy');
        that.getProperty("getProperty");
        that.getHydropower("getHydropower");
        that.initImgUpload("ly_1");
        that.clickAddImgDiv(type);
    },
    //获取楼宇列表
    getLyList: function (toPage) {
        if (!$("#tabLy").is(":visible")) return false;
        var that = this;
        var tbody = $("#tbodyLy");
        var page = $(".paginationWrapLy");
        var countryVal = $("#schAreaLy").val();
        var country = (countryVal == "0") ? countryVal : $("#schAreaLy option:selected").text();
        var name = $("#schLyInp").val();
        var page_size = page.attr("data-size");
        var param = {
            province: $("#schProLy").val(),
            city: $("#schCityLy").val(),
            country: country,
            name: name,
            page: toPage,
            page_size: page_size ? page_size : 10,
            trade_area: $("#tradeAreaLy").val(),
            is_delete: $("#isdelLy").val()
        };
        var thCnt = $("#lyThead th").size();
        that.loadCntBox();
        ZFT.Util.Ajax(
            "/r/building_getBuilding",
            {
                type: "POST",
                dataType: "json",
                params: param,
                loading: function () {
                    var html = '<tr><td colspan="' + thCnt + '">加载中,请稍后...</td></tr>'
                    tbody.html(html);
                    page.hide();
                },
                success: function (res) {
                    var data = res.data;
                    var list = data.list;
                    var render = ZFT.Util.ParseTemplate(Ly);
                    var dtype = data.dtype;
                    var pers = that.pers;
                    if (res.code == 200) {
                        if (list) {
                            for (var i = 0, len = list.length; i < len; i++) {
                                var item = list[i];
                                var prov = item.province;
                                var city = item.city;
                                var area;
                                if (!prov) continue;
                                area = that.getLocationName(prov, city);
                                item["city_area"] = area;
                            }
                        } else {
                            tbody.html('<tr><td colspan="' + thCnt + '">暂无数据</td></tr>');
                            return false;
                        }
                        list["dtype"] = dtype;
                        list["unsetBtn"] = ($.inArray("35", pers) !== -1) ? 1 : 0;
                        list["delBtn"] = ($.inArray("36", pers) !== -1) ? 1 : 0;
                        var html = render({ array: list });
                        tbody.html(html);
                        that.paginationLy.render({ current: toPage, toPage: toPage, total: data.total });
                    } else if (res.code == 102) {
                        var relogin = '<tr><td colspan="' + thCnt + '"><a href="/index/index/login">未登录,请重新登录</a></td></tr>'
                        tbody.html(relogin);
                    } else {
                        var html = '<tr><td colspan="' + thCnt + '">' + res.msg + '</td></tr>'
                        tbody.html(html);
                    }
                }
            })
    },
    //显示新增房源div
    addFy: function () {
        var that = this;
        var fyModal = Template.fymodal();
        var type = "fy";    //其他房源图
        var typeHx = "fyhx"; //房源户型
        $("#modal").html(fyModal)
        that.initLocation('schProFy', 'schCityFy', 'schAreaFy');
        that.getAllBuilding();  //新增房源时获取楼宇信息
        that.getOwner();
        that.changeFeeType();  //切换房租类型
        that.initImgUpload("fyhx_1");
        that.initImgUpload("fy_1");
        that.clickAddImgDiv(type);
        that.clickAddImgDiv(typeHx);

    },

    //获取物业公司
    getProperty: function (property_id, propertyId) {
        var property = $("#" + property_id);
        // if ($("#getProperty option").size() > 1) return false;
        ZFT.Util.Ajax(
            '/r/member_getProperty',
            {
                type: "POST",
                dataType: "json",
                success: function (res) {
                    var list = res.data.list;
                    var render = ZFT.Util.ParseTemplate(Company);
                    if (propertyId) list["id"] = propertyId;
                    switch (res.code) {
                        case 200:
                            var html = render({ companyArr: list });
                            property.append(html);
                            break;
                    }

                }
            }
        )
    },
    //获取水电公司
    getHydropower: function (hydropower_id, hydropowerId) {
        var property = $("#" + hydropower_id);
        //if ($("#getHydropower option").size() > 1) return false;
        ZFT.Util.Ajax(
            '/r/member_getHydropower',
            {
                type: "POST",
                dataType: "json",
                success: function (res) {
                    var list = res.data.list;
                    var render = ZFT.Util.ParseTemplate(Company);
                    if (hydropowerId) list["id"] = hydropowerId;
                    switch (res.code) {
                        case 200:
                            var html = render({ companyArr: list });
                            property.append(html);
                            break;
                    }
                }
            });
    },

    //新增或编辑房源
    editOrSaveFy: function (e) {
        var that = this;
        var tarBtn = $(e.currentTarget);
        var type = tarBtn.attr("data-type");
        var id = tarBtn.attr("data-id");
        var formData = {

            building_id: $("#getLyName").val(),
            number: $("#fyNumber").val(),
            floor: $("#fyFloor").val(),
            room: $("#fyRoom").val(),
            area: $("#fyArea").val(),
            price: $("#fyPrice").val(),
            price_type: $("#fyPrice").attr("data-type"),
            price_water: $("#fyPriceWater").val(),
            price_power: $("#fyPricePower").val(),
            property: $("#fyProperty").val(),
            fee_water: $("#fyFeeWater").val(),
            fee_power: $("#fyFeePower").val(),
            owner_id: $("#owner").val(),

        }
        var type_photo = that.formatImgSrcToString("fyhx");
        var other_photo = that.formatImgSrcToString("fy");
        var old_type_photo = $("#oldHx").val();
        var old_other_photo = $("#oldOther").val();
        var edit_type_photo = that.formatImgSrcToString("edfyhx");
        var edit_other_photo = that.formatImgSrcToString("edfy");
        var others = $("#fyOthers").val();
        var regx = /^[0-9]*[0-9][0-9]*$/;            //正整数正则
        var regf = /^(?:[1-9]\d*|0)(?:\.\d+)?$/;  //正浮点型正则
        var regRoom = /^\d+(-\d+)*$/;    //正则匹配 房号 :102-109
        if (id) formData["id"] = id;
        if (others) formData["others"] = others;
        if (type_photo && type == "new") formData["type_photo"] = type_photo;
        if (other_photo && type == "new") formData["other_photo"] = other_photo;
        if (edit_type_photo && type == "edit") {
            formData["type_photo"] = edit_type_photo;
            formData["old_type_photo"] = old_type_photo;
        }
        if (edit_other_photo && type == "edit") {
            formData["other_photo"] = edit_other_photo;
            formData["old_other_photo"] = old_other_photo;
        }
        if (!regx.test(formData["number"]) || !regx.test(formData["floor"])) {
            return ZFT.Util.STip("fail", "缺少参数或参数有误!", 4000);

        } else if (!regf.test(formData["area"]) || !regf.test(formData["price"]) || !regf.test(formData["price_water"]) || !regf.test(formData["price_power"]) || !regf.test(formData["property"]) || !regf.test(formData["fee_water"]) || !regf.test(formData["fee_power"])) {
            return ZFT.Util.STip("fail", "缺少参数或参数有误!!", 4000)
        }
        //if (!regRoom.test(formData["room"])) return ZFT.Util.STip("fail", "房号输入有误!", 4000);


        // console.log(formData)
        ZFT.Util.Ajax(
            (type == "new") ? '/r/building_setHouse' : '/r/building_editHouse',
            {
                type: "POST",
                dataType: "json",
                params: formData,
                success: function (res) {
                    if (res.code == 200) {
                        ZFT.Util.STip("success", res.msg, 4000);
                        tarBtn.parents(".m-modal_bg").fadeOut(200);
                        that.getBuildingList(1);
                    } else if (res.code == 102) {
                        return ZFT.Util.STip("fail", "未登录,请重新登录", 4000, function () {
                            window.location.href = "/index/index/login";
                        });
                    } else {
                        return ZFT.Util.STip("fail", res.msg, 4000);
                    }
                }
            }
        )
    },
    //新增房源时获取楼宇信息
    getAllBuilding: function (building_id) {
        var getLyName = $("#getLyName"),
            that = this;
        //if ($("#getLyName").val() != "0") return false;
        ZFT.Util.Ajax(
            '/r/building_getAllBuilding',
            {
                type: "POST",
                dataType: "json",
                success: function (res) {
                    var list = res.data.list;
                    var render = ZFT.Util.ParseTemplate(LyName);
                    switch (res.code) {
                        case 200:
                            if (building_id) { list["bid"] = building_id }
                            var html = render({ nameArr: list });
                            getLyName.html(html);
                            var proId = $("#getLyName option:selected").attr("data-pro");
                            var cityId = $("#getLyName option:selected").attr("data-city");
                            var areaId = $("#getLyName option:selected").attr("data-country");
                            that.setBuildingArea(proId, cityId, areaId);
                            break;
                    }
                }
            })
    },


    //新增房源时获取楼宇信息同时设置楼宇所在区域
    setBuildingArea: function (proId, cityId, area) {
        var provSelect = $("#schProFy");
        var citySelect = $("#schCityFy");
        var areaSelect = $("#schAreaFy");
        ZFT.Util.Ajax(
            '/index/getAreaName.html',
            {
                type: "POST",
                dataType: "json",
                params: {
                    province: proId,
                    city: cityId,
                },
                success: function (res) {
                    var list = res.data.list;
                    switch (res.code) {
                        case 200:
                            for (var i in list) {
                                if (list[i].code == proId) {
                                    provSelect.html("<option value=" + list[i].code + ">" + list[i].name + "</option>");
                                } else if (list[i].code == cityId) {
                                    citySelect.html("<option value=" + list[i].code + ">" + list[i].name + "</option>");
                                }
                            }
                            if (area == 0) {
                                areaSelect.hide();
                            } else {
                                areaSelect.show().html("<option >" + area + "</option>")
                            }
                            break;
                    }
                }
            })
    },
    //改变楼宇信息时重新定义楼宇所在区域
    switchBuildingArea: function () {
        var that = this;
        var proId = $("#getLyName option:selected").attr("data-pro");
        var cityId = $("#getLyName option:selected").attr("data-city");
        var areaId = $("#getLyName option:selected").attr("data-country");
        that.setBuildingArea(proId, cityId, areaId);
    },
    //新增房源时获取业主信息
    getOwner: function (owner_id) {
        var owner = $("#owner");
        //   if ($("#owner option").size() > 1) return false;
        ZFT.Util.Ajax(
            '/r/member_getOwners',
            {
                type: "POST",
                dataType: "json",
                success: function (res) {
                    var list = res.data.list;
                    if (owner_id) list["id"] = owner_id;
                    var render = ZFT.Util.ParseTemplate(Company);
                    switch (res.code) {
                        case 200:
                            var html = render({ companyArr: list });
                            owner.append(html);
                            break;
                    }
                }
            })
    },
    //新增楼宇
    editOrSaveLy: function (e) {
        var _this = this;
        var tarBtn = $(e.currentTarget);
        var type = tarBtn.attr("data-type");
        var id = tarBtn.attr("data-id");
        var schAreaFyLy = $("#schAreaFyLy");

        var regx = /^[0-9]*[0-9][0-9]*$/;
        var regxx = /^\w+$/;
        var formData = {
            province: $("#schProFyLy").val(),
            city: $("#schCityFyLy").val(),
            country: (schAreaFyLy.val() == "0") ? schAreaFyLy.val() : $("#schAreaFyLy option:selected").text(),
            name: $.trim($("#buildName").val()),
            type: $("#buildType").val(),
            address: $.trim($("#fyAddress").val()),
            property_id: $("#getProperty").val(),
            hydropower_id: $("#getHydropower").val(),
            building_number: $("#buildNumber").val(),
            building_count: $("#buildNum").val(),
            trade_area: $("#tradeArea").val(),
            fee_ratio: $("#feeRatio").val(),
            building_floor: $("#buildingFloor").val(),
            parking_num: $("#parkingNum").val(),
            lift_num: $("#liftNum").val()
        }
        var imgUrl = _this.formatImgSrcToString("ly");
        var edImgUrl = _this.formatImgSrcToString("edly");
        var oldPhoto = $("#oldPhoto").val();
        if (id) formData["build_id"] = id;
        if (imgUrl && type == "new") formData["photo"] = imgUrl;
        if (edImgUrl && type == "edit") {
            formData["photo"] = edImgUrl;
            formData["old_photo"] = oldPhoto;
        }
        if (formData["property_id"] == 0) return ZFT.Util.STip("fail", "请选择物业公司", 4000);
        if (formData["hydropower_id" == 0]) return ZFT.Util.STip("fail", "请选择水电公司", 4000);
        if (!formData["province"] || !formData["city"] || (schAreaFyLy).is(":visible") && schAreaFyLy.val() == 0) return ZFT.Util.STip("fail", "请选择楼宇所在区域!", 4000);
        if ($.trim(formData["address"]).length <= 0 || $.trim(formData["name"]).length <= 0) return ZFT.Util.STip("fail", "房源地址与楼宇名称不为空!", 4000);
        if (!regxx.test(formData["building_number"])) return ZFT.Util.STip("fail", "请输入正确的楼栋!", 4000);
        if (!regx.test(formData["building_count"])) return ZFT.Util.STip("fail", "楼宇数量仅为数字!", 4000);
        if (!regx.test(formData["parking_num"])) return ZFT.Util.STip("fail", "车位数量仅为数字!", 4000);
        if (!regx.test(formData["lift_num"])) return ZFT.Util.STip("fail", "电梯数量仅为数字!", 4000);
        ZFT.Util.Ajax(
            (type == "new") ? '/r/building_setBuilding' : '/r/building_editBuilding',
            {
                type: "POST",
                dataType: "json",
                params: formData,
                success: function (res) {
                    if (res.code == 200) {
                        ZFT.Util.STip("success", res.msg, 4000);
                        tarBtn.parents(".m-modal_bg").fadeOut(200);
                        _this.getLyList(1)
                    } else if (res.code == 102) {
                        return ZFT.Util.STip("fail", "未登录,请重新登录", 4000, function () {
                            window.location.href = "/index/index/login";
                        });
                    } else {
                        ZFT.Util.STip("fail", res.msg, 4000);
                    }
                }
            }
        )
    },
    //打开修改模态框
    openEditModal: function (e) {
        var tarBtn = $(e.currentTarget);
        var url;
        var param;
        var render;
        var _this = this;
        var id = tarBtn.attr("data-id");
        var type = tarBtn.parent().attr("data-type");
        if (type == "ly") {
            url = "/r/building_getBuildingDetail";
            param = {
                building_id: id
            }
        } else {
            url = "/r/building_getHouseDetail";
            param = {
                id: id
            };
        }
        ZFT.Util.Ajax(url, {
            type: "POST",
            dataType: "json",
            params: param,
            success: function (res) {
                var data = res.data;
                var photos = [];
                var photoOld = [];
                var photoHx = [];
                var hxUrl = [];
                var otherUrl = [];
                var pers = _this.pers;
                data["id"] = id;//将楼宇id或房源id赋值
                if (type == "ly") {

                    if (data.photo) {
                        for (var i in data.photo) {
                            photoOld.push(data.photo[i].url);
                            _this.initImgUpload("edly_" + i);
                        }
                        data["old_photo"] = photoOld.join(",");
                    }
                    data["editPer"] = ($.inArray("44", pers) !== -1) ? 1 : 0;
                    render = Template.editlymodal({ data: data });
                    $("#modal").html(render);
                    _this.getProperty("getProperty", data.property_id);
                    _this.getHydropower("getHydropower", data.hydropower_id);
                    _this.clickAddImgDiv("edly");
                    _this.initLocation("schProFyLy", "schCityFyLy", "schAreaFyLy", data.province, data.city);
                    _this.ajaxRenderDistrict(data.city, "schAreaFyLy", data.country);

                } else {
                    if (data.code != 200) {
                        ZFT.Util.STip("fail", data.msg, 4000)
                    }
                    //将图片分成2组
                    if (data.photo) {
                        for (var i in data.photo) {
                            if (data.photo[i].srtype == 1) {

                                hxUrl.push(data.photo[i].url);
                                photoHx.push({ srtype: 1, url: data.photo[i].url });
                                _this.initImgUpload("edfyhx_" + i);
                            } else {
                                otherUrl.push(data.photo[i].url);
                                photos.push({ srtype: 2, url: data.photo[i].url })
                                _this.initImgUpload("edfy_" + i);
                            }
                        }
                        data["photohx"] = photoHx;
                        data["photos"] = photos;
                        data["oldhx"] = hxUrl.join(",");
                        data["oldother"] = otherUrl.join(",");

                    }
                    data["editPer"] = ($.inArray("43", pers) !== -1) ? 1 : 0;
                    render = Template.editfymodal({ data: data });
                    $("#modal").html(render);
                    //console.log($("#oldHx").val(),$("#oldOther").val())
                    _this.initLocation('schProFy', 'schCityFy', 'schAreaFy');
                    _this.getAllBuilding(data.building_id);
                    _this.getOwner(data.mid);
                    if (data.photo) {
                        for (var i in data.photo) {
                            _this.initImgUpload("edfyhx_" + i);
                            _this.initImgUpload("edfy_" + i);
                        }
                    }
                    _this.clickAddImgDiv("edfy");
                    _this.clickAddImgDiv("edfyhx");

                }

            }
        });
        /*$(".cancel,.close").on("click", function (e) {
            _this.closeModal(e);
        });*/
    },

    closeModal: function (e) {
        var tarBtn = $(e.currentTarget);
        tarBtn.parents(".m-modal_bg").fadeOut(200);
    },
    //失效或删除模态框
    openStatusModal: function (e) {
        var tarBtn = $(e.currentTarget);
        var _this = this;
        var build_id = tarBtn.attr("data-id");
        var ctype = tarBtn.attr("data-type");//获取操作类型 del 删除,inv 失效
        var type = tarBtn.parent().attr("data-type");
        var title = (type == "ly") ? "楼宇" : "房源";
        var data = {
            build_id: build_id,
            title: title,
            ctitle: (ctype == "del") ? "删除" : "失效",
            type: type,
            ctype: ctype
        }
        var render = ZFT.Util.ParseTemplate(OptModal);
        var html = render({ data: data });
        $("#modal").html(html);

    },

    //删除或失效房源楼宇请求
    onClickModalConfBtn: function (e) {
        var tarBtn = $(e.currentTarget);
        var _this = this;
        var build_id = tarBtn.attr("data-id");
        var type = tarBtn.attr("data-type");
        var ctype = tarBtn.attr("data-ctype");
        var url;
        var param;
        if (type == "ly") {
            param = {
                build_id: build_id ? build_id : ""
            }
            if (ctype == "del") {
                url = "/r/building_deleteBuilding";
            } else {
                url = "/r/Building_setForbidBuilding";
                param["status"] = 1;
            }

        } else {
            param = {
                id: build_id ? build_id : ""
            }
            if (ctype == "del") {
                url = "/r/building_deleteHouse";
            } else {
                url = "/r/Building_setForbidHouse";
                param["status"] = 1;
            }
        }
        ZFT.Util.Ajax(url, {
            type: "POST",
            dataType: "json",
            params: param,
            success: function (res) {
                if (res.code == 200) {
                    tarBtn.parents(".m-modal_bg").fadeOut(200);
                    if (type == "ly") {
                        _this.getLyList(1)
                    } else {
                        _this.getBuildingList(1)
                    }
                    return ZFT.Util.STip("success", res.msg, 3000);

                } else {
                    tarBtn.parents(".m-modal_bg").fadeOut(200);
                    return ZFT.Util.STip("fail", res.msg, 3000);
                }
            }

        })
    },

    //删除当前图片上传的容器
    onClickImgDivDelbtn: function (e) {
        var tarBtn = $(e.currentTarget);
        tarBtn.parents(".lt").hide(200, function () {
            tarBtn.parents(".lt").remove();
        });
    },
    //初始化图片上传插件
    initImgUpload: function (i) {
        var uploadorname = $("#imgLoaderContainer_" + i).find("input[name=callback]").val();
        if (uploadorname) {
            uploadorname = uploadorname.split(".")[0];
            window[uploadorname] = new ImgUploador({ container: $("#imgLoaderContainer_" + i) });
        }
    },
    //点击图片添加按钮
    clickAddImgDiv: function (type) {
        var that = this;
        var i = 1;
        var addImgDiv;
        var addImgDivId;
        if (type == "ly") {
            addImgDivId = "#addLyImgDiv";
        } else if (type == "fy") {
            addImgDivId = "#addFyImgDiv";
        } else if (type == "fyhx") {
            addImgDivId = "#addFyHxImgDiv";
        } else if (type == "edly") {
            addImgDivId = "#addEdLyImgDiv";
        } else if (type == "edfy") {
            addImgDivId = "#addEdFyImgDiv";
        } else if (type == "edfyhx") {
            addImgDivId = "#addEdFyHxImgDiv";
        }
        $(addImgDivId).on("click", function (e) {
            ++i;
            var tarBtn = $(e.currentTarget);
            if (type == "ly") {
                addImgDiv = Template.addlyimg({ i: type + "_" + i });
            } else if (type == "fy") {
                addImgDiv = Template.addfyimg({ i: type + "_" + i });
            } else if (type == "fyhx") {
                addImgDiv = Template.addfyimg({ i: type + "_" + i });
            } else if (type == "edly") {
                addImgDiv = Template.addlyimg({ i: type + "_" + i });
            } else if (type == "edfy") {
                addImgDiv = Template.addfyimg({ i: type + "_" + i });
            } else if (type == "edfyhx") {
                addImgDiv = Template.addfyimg({ i: type + "_" + i });
            }
            tarBtn.parents(".fbox.lt").before(addImgDiv);
            that.initImgUpload(type + "_" + i);
            //  console.log(tarBtn,i)
        })

    },
    //提交新增请求时循环图片将地址拼接成一个字符串
    formatImgSrcToString: function (type) {
        var imgUrl;
        var imgDiv;
        var array = [];
        if (type == "ly") {
            imgDiv = "#lyUploadBox";
        } else if (type == "fy") {
            imgDiv = "#fyUploadBox";
        } else if (type == "fyhx") {
            imgDiv = "#fyHxUploadBox";
        } else if (type == "edly") {
            imgDiv = "#edlyUploadBox";
        } else if (type == "edfy") {
            imgDiv = "#edfyUploadBox";
        } else if (type == "edfyhx") {
            imgDiv = "#edfyHxUploadBox";
        }
        $.each($(imgDiv + " .hidInp_imgurl"), function (i, url) {
            if ($(url).val()) {
                array.push($(url).val());
            }
        })
        imgUrl = array.join(",");
        return imgUrl;
    },
    //切换房租类型
    changeFeeType: function () {
        $("#priceType").on("change", function (e) {
            var tarBtn = $(e.currentTarget);
            $("#fyPrice").attr({ "placeholder": (tarBtn.val() == 1) ? "元/㎡" : "元/月", "data-type": tarBtn.val() }).val("");
        })
    },
    //点击楼宇的区域时房源管理展示对应信息
    onClickAreaTd: function (e) {
        var _this = this;
        var tarTd = $(e.currentTarget);
        var id = tarTd.attr("data-id");
        $("#tabFy").click();
        $("#schFy").attr("data-id", id);
        _this.getBuildingList(1);
    }

});


$(function () {
    new Building();
})